<template>
	<view class="">
		<headerinfo></headerinfo>
		<view class="width60" style="background-color: #fff;">
			<view class="friend_Page">
				<view class="chatAiBg"></view>
				<u-navbar :title="guanxi"  leftIconColor="#fff" :autoBack="true" :bgColor="bgColor"
					:titleStyle="titleStyle"></u-navbar>
				<view class="tips color_fff size_12 align_c" :class="{ show: ajax.loading }" @tap="getHistoryMsg">
					{{ ajax.loadText }}
				</view>
			
				<view class="box-1" id="list-box">
					<view class="talk-list">
						<view v-for="(item, index) in talkList" :key="index" :id="`msg-${item.docId}`">
							<view class="item flex_col" :class="item.type == 1 ? 'push' : 'pull'">
								<image v-if="item.type == 1" :src="avatar" mode="aspectFill" class="pic"></image>
								<image v-else :src="otheravatar?otheravatar:'../../static/images/robbot.png'" mode="aspectFill"
									class="pic"></image>
								<view class="content" >{{ item.content }}</view>
			
							</view>
							<view class="" :style="{ height:(keyboardHeight)+'px'}"></view>
						</view>
					</view>
				</view>
				<view class="box-2" >
					<view class="flex_col">
			
						<view class="flex_grow">
							<textarea class="textareas" maxlength="256" v-model="content" placeholder="请输入聊天内容"
								placeholder-style="color:#adb1b9;" :adjust-position="false"></textarea>
			
							<!-- 	<input type="text" maxlength="256" class="content" v-model="content" placeholder="请输入聊天内容"
								placeholder-style="color:#DDD;" :cursor-spacing="6" /> -->
						</view>
						<button class="send" @tap="send">发送</button>
					</view>
			
			
				</view>
			
			
			</view>
		</view>
	</view>
	
</template>

<script>
	import {
		fetchEventSource
	} from "@microsoft/fetch-event-source";
	import * as TextEncoding from 'text-encoding-shim';
	import {
		apiBaseURL
	} from '../../common/config.js'
	import minxins from '../../common/upload.js';
	export default {
		mixins: [minxins],
		data() {
			return {
				username:'',  // 对方的username
				yuyingDia:false,
				lang: '',
				langdia: false,
				selectorVisible: false,
				selectdefaultProps: {
					label: "name",
					value: "id"
				},
				selectorList: [{
					name: "文本",
					id: "text"
				}, {
					name: "语音",
					id: "voice"
				}, {
					name: "视频",
					id: "video"
				}],
				yuyinglist: [{
					name: "自定义声音",
					id: "1"
				}, {
					name: "系统声音",
					id: "2"
				}],
				lanlist: [],
				guanxi: '',
				bgColor: '#de4849',
				titleStyle: {
					color: '#fff'
				},
				talkList: [],
				ajax: {
					pageSize: 20, //每页数量
					lastDocId: '', //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息',
					familyMemberId: '',
					fanUsername:''
				},
				//我们的字段
				content: '',
				nowIndex: -1,
				requestTask: null,
				background: 'https://www.25175.net/images/mybg.jpg',
				useColorAsBg: true,
				avatar: '', //我的头像
				otheravatar: '', //我的头像
				answerMode: 'text',
				safeAreaInsets: {},
				keyboardHeight: 0,
				innerAudioContext: null,
				aiavatar: '',
				issetVideo:false,
				useMemberSelfVoice:false
			};
		},
		onLoad(e) {
			
			if(e.username){
				this.ajax.fanUsername = this.username = e.username
			}
			if (e.avatar) {
				this.aiavatar = e.avatar
			}

		},
		onUnload() {
			// 页面销毁时移除监听
			uni.offKeyboardHeightChange();
		},
		onShow() {
			this.getData()
			
			const {
				safeAreaInsets
			} = uni.getSystemInfoSync()
			this.safeAreaInsets = safeAreaInsets


			//  监听键盘高度变化
			uni.onKeyboardHeightChange((res) => {
				// 获取系统信息
				if (res.height) {
					let _sysInfo = uni.getSystemInfoSync()
					let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
					let _diff = res.height - _heightDiff
					this.keyboardHeight = _diff > 0 ? _diff : 0


					//  let deviceBottom= this.safeAreaInsets.bottom;  
					//  this.keyboardHeight = res.height ? (res.height - deviceBottom - deviceBottom) : 0  
				} else {
					this.keyboardHeight = 0
				}
			})


		},
		mounted() {
			this.$nextTick(() => {
				this.getHistoryMsg();
				this.getAvatar();
				this.innerAudioContext = uni.createInnerAudioContext();
				
				
				this.$api2.messageRead({fanUsername:this.username}).then(res => {
					console.log('消息已读')
				})
				
			});
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
					duration: 0
				});
			}, 500)
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}

		},
		methods: {
			getData() {
				this.$api.getChatConfig().then(res => {
					console.log(res)
					if (res.background) {
						this.background = res.background
						this.useColorAsBg = res.useColorAsBg
					}
				})
			},
			
			yuyingCheck(e) {
				if(e.value == 1){
					this.useMemberSelfVoice = true
				}else{
					this.useMemberSelfVoice = false
				}
			},
			langchecked(e) {
				console.log(e)
				this.lang = e.value
			},
			//获取自己的头像
			getAvatar() {
				this.$api.myInfo().then(res => {
					console.log(res)
					this.avatar = res.avatar;
				})
			},
			// 获取历史消息
			getHistoryMsg() {


				if (!this.ajax.flag) {
					return;
				}
				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					let data = await this.joinHistoryMsg();
					
					console.log('消息历史')
					console.log(data)


					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.lastDocId) {
						// 非第一页，则取历史消息数据的第一条信息元素
						if (this.talkList.length > 0) {
							selector = `#msg-${this.talkList[0].docId}`;
						}
					} else {
						if (data.length > 0) {
							// 第一页，则取当前消息数据的最后一条信息元素
							selector = `#msg-${data[data.length - 1].docId}`;
						}
					}

					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];
					
					console.log('this.talkList')
					console.log(this.talkList)
					// if (this.talkList.length == 0) {
					// 	this.talkList.push({
					// 		content: '我是您的AI管家，有什么问题尽管向我提问吧',
					// 		type: 2
					// 	})
					// }

					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);
						this.hideLoadTips(true);

						if (this.ajax.lastDocId) {
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200);
						} else {}
					});
				};
				get();
			},
			// 历史记录接口
			joinHistoryMsg() {
				// 此处用到 ES6 的 Promise 知识，不懂的请自行学习。
				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 ajax 即可。
					let arr = [];
					let myusername = uni.getStorageSync('username')?uni.getStorageSync('username'):''
					this.$api2.getUserMessage(this.ajax).then(res => {
						arr = res.messages[0].messageList
						this.guanxi = res.messages[0].showName 
						this.otheravatar = res.messages[0].avatar 
						
						
						arr.reverse()
						
						if(arr.length>0){
							arr.forEach(item2=>{
								if(item2.senderId == myusername){
									item2.type = 1
								}else{
									item2.type = 2
								}
							})
						}
						done(arr)
						
					})

				});
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni
					.createSelectorQuery()
					.in(this)
					.select(selector);
				view.boundingClientRect(res => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			spliteDecode(value) {
				var target = value.match(/\\u\d+/g);
				if (target && target.length > 0) {
					target = target[0];
					var temp = value.replace(target, '{{@}}');
					target = target.replace('\\u', '');
					target = String.fromCharCode(parseInt(target));
					return temp.replace("{{@}}", target);
				} else {
					// value = value.replace( '\\u', '' );
					// return String.fromCharCode( parseInt( value, '10' ) )
					return value;
				}
			},
			bofang(url) {
				
				
				// 停止当前播放
				this.innerAudioContext.stop();
				// 清除当前音频源
				this.innerAudioContext.src = url;
				// 播放音频
				this.innerAudioContext.play();
			},
			toSetLuying(){
			   uni.navigateTo({
					url:`/pages/chat/videoset?familyMemberId=${this.familyMemberId}`
			   })	
			},
			copy(msg) {
				uni.setClipboardData({
					data: msg, // e是你要保存的内容
					success: function() {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					}
				})
			},
			uploadVideo() {
				// 选择音频文件
				uni.chooseMedia({
					count: 1, // 默认选取一个媒体文件
					mediaType: ['audio'], // 只选择音频文件
					success: (res) => {
						// 获取到了音频文件
						const tempFilePaths = res.tempFiles[0].tempFilePath;
						console.log(res)
						
						// 限制 300K

						var fileName = Date.now() + '_' + Math.round(Math.random() *
							100000000) + '.' + tempFilePaths.substring(tempFilePaths.lastIndexOf(
							'.') + 1)

						var familyId = uni.getStorageSync('familyId') ? uni
							.getStorageSync('familyId')[0] : ''


						this.uploadUserImage(tempFilePaths, 'image', fileName, familyId, (
							imgUrl) => {
							console.log(imgUrl)

							let data = {
								familyMemberId: this.familyMemberId,
								soundFile: imgUrl
							}
							this.$api.uploadFamilyMemberSound(data).then(res => {
								this.$Show.show('设置成功')
							})
						})
					}
				});
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					});
					return;
				}


				let dataInfo = {
					content: this.content,
					receiveUsername:this.username,
					businessName:'',
					type:1,
					userId:'',
					username:'',
				};
				
				this.$api2.sendMessag(dataInfo).then(res=>{
					this.talkList.push(dataInfo);
					this.ajax.flag = true
					
					// this.getHistoryMsg()
				})


				// this.nowIndex = this.nowIndex + 2

				// let dataInfo2 = {
				// 	content: '',
				// 	type: 2,
				// 	avatar: this.avatar,
				// 	receiveUsername:this.username
				// };

				// this.talkList.push(dataInfo2);
				
				

				this.$nextTick(() => {
					// 清空内容框中的内容
					this.content = '';
					uni.pageScrollTo({
						scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
						duration: 0
					});
				});

			},
			toSetting() {
				uni.navigateTo({
					url: '/pages/chat/setting'
				})
			},
			selectonConfirm(e) {
				console.log(e)
				this.answerMode = e.value
			}
		}
	};
</script>

<style lang="scss">
	@import './global.scss';

	.chatAiBg {
		background-size: cover !important;
		background-repeat: no-repeat;
		background-attachment: fixed;
		height: 100vh;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 100rpx;
		z-index: -100;
	}

	.setting {
		display: flex;
		align-items: center;
		background-color: #de4849;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		border-radius: 20rpx;
		color: #fff;

		.iconfont {
			font-size: 34rpx;
			margin-left: 10rpx;
		}
	}

	.change {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-right: 20rpx;
	}

	page {
		background-color: #f3f3f3;
		font-size: 28rpx;
	}

	.copyText {
		padding: 0 20rpx;
		color: #8f8f8f;
	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #f3f3f3;


		>view {
			padding: 20rpx;
		}

		.textareas {
			background-color: #fff;
			height: 200rpx;
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
			width: 98%;
			box-sizing: border-box;
		}

		.content {
			background-color: #fff;
			height: 124rpx;
			padding: 0 20rpx;
			border-radius: 10rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #de4849;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 80rpx;
		min-height: 60vh;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
			}

			.content {
				padding: 10rpx 15rpx;
				border-radius: 4px;
				max-width: 590rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 20rpx;
					background-color: #f5f6f8;
					border: 1px solid #e7e8ea;
					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-right: 20rpx solid #fff;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	left: -18rpx;
					// }
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 20rpx;
					background-color: #e6f7ff;
					border: 1px solid #223850;

					// &::after {
					// 	content: '';
					// 	display: block;
					// 	width: 0;
					// 	height: 0;
					// 	border-top: 16rpx solid transparent;
					// 	border-bottom: 16rpx solid transparent;
					// 	border-left: 20rpx solid #a0e959;
					// 	position: absolute;
					// 	top: 16rpx;
					// 	right: -18rpx;
					// }
				}
			}
		}
	}
	.updatevideo{
		color: #de4849;	
	}

	.seeVideo2 {
		width: 600rpx;
		height: 600rpx;
		overflow: hidden;

		video {
			width: 100%;
			height: 82%;
		}

		.createBtn {
			width: 62%;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #de4849;
			color: #fff;
			border-radius: 10rpx;
			margin: 15rpx auto;
			font-size: 28rpx;
		}
	}

	.seeVideo {
		width: 600rpx;
		overflow: hidden;


		image {
			width: 100%;
			height: auto;
		}

		view {
			text-align: center;
			margin: 30rpx 0;
			font-size: 38rpx;
		}
	}

	.setboxlist {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.list {
			width: 32%;
		}
	}
</style>